package cn.xiaolang.thread.threadpool;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadPoolExecutor;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

/**
 * spring-context包下的 {@code ThreadPoolTaskExecutor}对
 * {@code ThreadPoolExecutor}的封装
 *
 * @author fuhw/Dean
 */
@Slf4j
public class ThreadPoolTaskExecutorStarted {

    public static void main(String[] args) {
        ThreadPoolTaskExecutor threadPoolExecutor = new ThreadPoolTaskExecutor();
        threadPoolExecutor.setCorePoolSize(5);
        /**
         * 推荐设置为：可用core*2
         * Runtime.getRuntime().availableProcessors()*2
         */
        threadPoolExecutor.setThreadNamePrefix("spring-pool-thread-");
        threadPoolExecutor.setMaxPoolSize(10);
        threadPoolExecutor.setQueueCapacity(3);
        threadPoolExecutor.setWaitForTasksToCompleteOnShutdown(Boolean.TRUE);
        threadPoolExecutor.setKeepAliveSeconds(0);
        threadPoolExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());
        threadPoolExecutor.initialize();
        CountDownLatch countDownLatch = new CountDownLatch(13);


        for (int i = 0; i < 50; i++) {
            log.info("添加任务{}", i);
            threadPoolExecutor.execute(() -> {
                log.info("active:{},poolSize:{},queueSize:{}"
                        , threadPoolExecutor.getActiveCount()
                        , threadPoolExecutor.getPoolSize(), threadPoolExecutor.getThreadPoolExecutor().getQueue().size());
                try {
                    Thread.sleep(1000 * 10);
                } catch (InterruptedException e) {
                    log.error("", e);
                } finally {
                    countDownLatch.countDown();
                }
            });
        }

        try {
            threadPoolExecutor.shutdown();
            countDownLatch.await();
            log.info("all thread execute over!");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


}

